package com.lagou.transfer.dao.impl;

import com.lagou.transfer.dao.BankDao;
import com.lagou.transfer.pojo.Bank;
import com.spring.annotation.Autowired;
import com.spring.annotation.Repository;
import com.spring.aop.DataSourceHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class BankDaoImpl implements BankDao {
    @Autowired
    private DataSourceHandler dataSourceHandler;

    @Override
    public List<Bank> select() {
        Connection connection = dataSourceHandler.getConnection();
        String sql = "select * from bank";
        try {
            List<Bank> banks = new ArrayList<>();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                String bankCardNo = resultSet.getString("bankCardNo");
                float money = resultSet.getFloat("money");
                Bank bank = new Bank(name, bankCardNo, money);
                banks.add(bank);
            }
            return banks;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Integer update(Bank bank) {
        Connection connection = dataSourceHandler.getConnection();
        System.out.println("修改方法");
        System.out.println(connection);
        String sql = "update bank set money=? where bankCardNo=?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1, bank.getMoney());
            preparedStatement.setObject(2, bank.getBanCardNo());
            int i = preparedStatement.executeUpdate();
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Bank selectOne(String cardNo) {
        Connection connection = dataSourceHandler.getConnection();
        String sql = "select * from bank where bankCardNo = ?";
        try {
            Bank bank = null;
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1, cardNo);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String name = resultSet.getString("name");
                String bankCardNo = resultSet.getString("bankCardNo");
                float money = resultSet.getFloat("money");
                bank = new Bank(name, bankCardNo, money);
            }
            return bank;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

}
